package com.hetang.maijiayun.adaptertools.adapter;

import com.hetang.maijiayun.adaptertools.controller.vo.request.DetectorRequest;
import com.hetang.maijiayun.adaptertools.utils.JsonTools;
import com.hetang.maijiayun.adaptertools.utils.Util;
import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.domain.order.OrderSearchInfo;
import com.jd.open.api.sdk.request.order.OrderSearchRequest;
import com.jd.open.api.sdk.response.order.OrderSearchResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.http.impl.cookie.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by wanda on 11/3/15.
 */
public class JdAdapter extends AdapterAbstract {
    /**
     * 日志
     */
    private static final Logger logger = LoggerFactory.getLogger(JdAdapter.class);

    @Override
    public Integer request(Map<String, String> authorizesMap, DetectorRequest request) throws Exception {
        return null;
    }

    @Override
    public List<String> requestOrders(Map<String, String> authorizesMap, DetectorRequest request) throws Exception {
        if (MapUtils.isEmpty(authorizesMap) || !authorizesMap.containsKey("url") || !authorizesMap.containsKey("appKey") || !authorizesMap.containsKey("secret") || !authorizesMap.containsKey("sessionKey")) {
            logger.error("该京东平台店铺没有授权信息或授权信息错误！！");
            return null;
        }
        DefaultJdClient client = new DefaultJdClient(authorizesMap.get("url"), authorizesMap.get("sessionKey"), authorizesMap.get("appKey"), authorizesMap.get("secret"));
        OrderSearchRequest req = new OrderSearchRequest();
        req.setOptionalFields("order_id,order_total");

        req.setOrderState("WAIT_SELLER_STOCK_OUT,WAIT_GOODS_RECEIVE_CONFIRM,FINISHED_L,TRADE_CANCELED");
        req.setStartDate(DateUtils.formatDate(request.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
        req.setEndDate(DateUtils.formatDate(request.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
        req.setPage("1");
        req.setPageSize("50");
        logger.info("jd get order interface, request time is : {}, request param is : {}", System.currentTimeMillis(), JsonTools.createJsonString(req));
        OrderSearchResponse rsp = client.execute(req);
        logger.info("jd get order interface, response time is : {}, response : {}", System.currentTimeMillis(), JsonTools.createJsonString(rsp));
        if (rsp == null || !"".equals(rsp.getCode())) {
            return null;
        }
        Long page = 0L;
        Long mod = rsp.getOrderInfoResult().getOrderTotal() % 50L;
        page = rsp.getOrderInfoResult().getOrderTotal() / 50L;
        if (0 != mod) {
            page += 1;
        }
        List<String> result = new ArrayList<String>();
        while (page > 0) {
            req.setPage(page.toString());
            rsp = client.execute(req);
            if (!"".equals(rsp.getCode())) {
                logger.error("jd get order interface error, response time is : {}, response : {}", System.currentTimeMillis(), JsonTools.createJsonString(rsp));
                continue;
            }
            if (CollectionUtils.isEmpty(rsp.getOrderInfoResult().getOrderInfoList())) {
                continue;
            }
            for (OrderSearchInfo orderInfo : rsp.getOrderInfoResult().getOrderInfoList()) {
                result.add(orderInfo.getOrderId() + "");
            }
            page--;
        }
        return result;
    }
}
